<?php
/**
 * Users AR class file.
 * --------------------
 * User validation business rules and authentication
 *
 * LICENSE: BSD
 * @copyright  2009 Gemisoft
 * @author Deepak Pradhan <deepak.pradhan@gemisoft.com>
 * @link http://grbac.gemisoft.com/
 * @version $Id$
 * @since 0.1
 */

class Users extends CActiveRecord {
/**
 * The followings are the available columns in table 'users':
 * @var int    id
 * @var string username
 * @var string password
 * @var string namef - name first
 * @var string namem - name middle
 * @var string namel - name last
 * @var string email
 * @var string created	- datetime
 * @var string lastlogin - on update CURRENT_TIMESTAMP
 * @var string valid_code
 * @var string authorize
 * @var string active - boolean
 * @var string webservice - boolean
 * @var string center
 * @var string algo - what algo is used to encrypt
 */

  /* @var boolean - Is authentication request from web sevice */
  public $isWebservice = false;

  /* @var string - capta input dtring received from user*/
  public $captcha;

  /* @var string -  */
  public $passwordOld;

  /* @var string - */
  public $passwordNew;

  /* @var string - */
  public $passwordNew_repeat;

  /* @var string - */
  public $rememberMe=false;

  /**
   * Returns the static model of the specified AR class.
   * @return CActiveRecord the static model class
   */
  public static function model($className=__CLASS__) {
    return parent::model($className);
  }

  /**
   * @return string the associated database table name
   */
  public function tableName() {
    return 'users';
  }

  /**
   * @return array validation rules for model attributes.
   */
  public function rules() {
    return array(
    array('username','length','max'=>45),
    array('active', 'numerical', 'integerOnly'=>true),
    array('center', 'numerical', 'integerOnly'=>true),
    array('email','CEmailValidator'),

    array('active', 'required', 'on'=>'togle'),
    array('active', 'required', 'on'=>'register_validation'),

    // on login:
    array('username, password', 'required', 'on'=>'login'),
    array('password', 'authenticateLogin', 'on'=>'login'),

    // on personal info update:
    array('username, namef, namel, email', 'required', 'on'=>'update'),

    // on personal info update:
    array('passwordNew, passwordNew_repeat, passwordOld', 'required', 'on'=>'password_change'),
    );
  }

  /**
   * Authenticates the password.
   * This is the 'authenticate' validator as declared in rules().
   * invokes custom UserIdentity defined in grbac's component
   */
  public function authenticateLogin($attribute,$params) {
  //	echo "\nAttribute:".print_r($attribute);
  //	echo "\nParams:".print_r($this->hasErrors());
    if(!$this->hasErrors())  // we only want to authenticate when no input errors
    {
      $identity = new UserIdentity($this->username, $this->password);
     // print_r($identity);
      $identity->authenticate();

      Yii::app()->user->login($identity);

      switch($identity->errorCode) {
        case CUserIdentity::ERROR_NONE:
          if(Yii::app()->getModule('grbac')->enableRemember) {
            $duration = 3600 * 24 * Yii::app()->getModule('grbac')->durationRemember;
            if ($this->webservice) {  // Not implemented
              $duration = 3600 * 2; // 2 hours
            }
          } else {
            $duration = 0;
          }
          Yii::app()->user->login($identity, $duration);

          $user=Users::model()->findByAttributes(array('username'=>$this->username));
          $user->auth_code  = ($this->webservice) ? $this->WSAuthorizeCode : '';
          $user->webservice = ($this->webservice) ? 1 : 0;
          $user->saveAttributes(array('auth_code','webservice'));
          break;
        default: // UserIdentity::ERROR_PASSWORD_INVALID
          if ($identity->errorCode == 9) {
            $this->addError('username','החשבון מחכה לאישור מנהל , או לחילופין מוקפא');
          }
          else {
            $this->addError('username','שם המשתמש אינו מוכר או');
            $this->addError('password','סיסמה לא נכונה');
          }
          break;
      }
    }
  }


  /**
   * @return array customized attribute labels (name=>label)
   */
  public function attributeLabels() {
    return array(
     'username' => 'שם משתמש'
    ,'password'=>'סיסמה'
    ,'rememberMe'=>'זכור אותי על המחשב הזה'
    ,'namef'=>'שם פרטי'
    ,'namem'=>'שם אמצעי'
    ,'namel'=>'שם משפחה'
    ,'center' => 'סניף'
    ,'passwordOld'=>'סיסמה ישנה'
    ,'passwordNew'=>'סיסמה חדשה'
    ,'passwordNew_repeat'=>'אימות סיסמה'
    ,'created'=>'נוצר'
    ,'lastlogin'=>'התחבר לאחרונה'
    ,'algo' => 'Hash Algorithm'
    );
  }

  public function safeAttributes() {
    return array(
    'login' => 'username, password, rememberMe',
    );
  }

  private function WSAuthorizeCode() {
  // Generate random Authorization Code for Web Service
  }

  public function WSAuthorizeCodeValidate() {
  // Validate Authorization and session
  }

  public function getUserMailList($center = 1)
  {
    $userList = array();
    $Criteria = new CDbCriteria();
    $Criteria->order = "namel ASC,namef ASC";
    $Criteria->select = "id,namef,namel";
    $Criteria->params = array (':center' => $center);
    if($center!=1)
        $Criteria->condition = "center = :center";
    $users=Users::model()->findAll($Criteria);
    foreach($users as $user)
        $userList[$user['id']] = implode(' ',array($user['namef'],$user['namel']));
    return $userList;
  }

}